package com.invengo.library_rfid.classify;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.os.Handler;

import com.invengo.device.DeviceHelper;
import com.invengo.library_rfid.callback.OnRegisterListener;
import com.invengo.library_rfid.callback.OnRfidResult;
import com.invengo.library_rfid.callback.StateChangeListener;
import com.invengo.library_rfid.entity.TagInfo;

import java8.util.Optional;

import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.bus._KeyState;
import me.goldze.mvvmhabit.service.IRfidEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class RFIDCallBackListener implements IRfidEvent {
    private OnRfidResult onRfidResult;
    private StateChangeListener stateChangeListener;
    private OnRegisterListener registerListener;

    public RFIDCallBackListener(AnalyzeImpl analyze, OnRfidResult onRfidResult, StateChangeListener listener) {
        this(analyze, onRfidResult, listener, null);
    }

    public RFIDCallBackListener(AnalyzeImpl analyze, OnRfidResult onRfidResult, StateChangeListener listener, OnRegisterListener registerListener) {
        this.onRfidResult = onRfidResult;
        this.stateChangeListener = listener;
        this.registerListener = registerListener;
        RxBus.getDefault().postSticky(analyze);
    }


    private String cacheKey;

    private Disposable resultDisposable, keyDisposable;


    public void registerEvent(String cacheKey) {
//        if (getCacheTag() == null)
//            return;
        if (onRfidResult == null) {
            KLog.e(cacheKey + "当前界面无需注册");
            return;
        }
        this.cacheKey = cacheKey;
        System.out.println("订阅第2步：订阅返回值和按键 [ " + cacheKey + " ]");
        resultDisposable = RxBus.getDefault().toObservable(TagInfo.class).subscribe(tagInfo -> {
            DeviceHelper.getInstance().playVoice();
            onRfidResult.onResult(tagInfo);
        });
        keyDisposable = RxBus.getDefault().toObservable(_KeyState.class).subscribe(keyState -> {
            switch (keyState) {
                case START:
                    System.out.println("开始扫描[" + cacheKey + "]");
                    stateChangeListener.onStateChange(true);
                    DeviceHelper.getInstance().startScan(cacheKey);
                    ToastUtils.showShort("开始扫描");
                    needShowStopToast = true;
                    break;
                case STOP:
                    stateChangeListener.onStateChange(false);
                    System.out.println("取消第1-2步：停止扫描功能 [ " + cacheKey + " ]");
                    DeviceHelper.getInstance().stopScan();
                    if (needShowStopToast) {
                        ToastUtils.showShort("停止扫描");
                        needShowStopToast = false;
                    }
                    break;
            }
        });
        RxSubscriptions.add(keyDisposable);
        RxSubscriptions.add(resultDisposable);
        System.out.println("订阅第3步：订阅完成 [ " + cacheKey + " ]");
        if (registerListener != null)
            registerListener.onRegister(cacheKey);
    }

    private boolean needShowStopToast = true;



    public void removeEvent() {
        Optional.ofNullable(getCacheKey()).ifPresent(fragmentTag -> {
            if (!keyDisposable.isDisposed()) {
                cleanRFIDCache();
                new Handler().postDelayed(() -> {
                    System.out.println("取消第3-1步：清理订阅 [ " + getCacheKey() + " ]");
                    keyDisposable.dispose();
                }, 30);
            }
            if (!resultDisposable.isDisposed()) {
                new Handler().postDelayed(() -> {
                    System.out.println("取消第3-2步：清理订阅 [ " + getCacheKey() + " ]");
                    resultDisposable.dispose();
                }, 30);
            }
        });
    }

    /**
     * 停止扫描
     */

    public void stopScan() {
        new Thread(() -> {
            try {
                System.out.println("取消第1步：发送9527停止扫描 [ " + getCacheKey() + " ]");
                new Instrumentation().sendKeyDownUpSync(9527);
            } catch (Exception e) {
            }
        }).start();
//        if (DeviceHelper.getInstance().isReading()){
//            changeScanState();
//        }
    }

    @Override
    public String getCacheKey() {
        return cacheKey;
    }

    @Override
    public void autoScan() {
        new Thread(() -> {
            try {
                System.out.println("发送虚拟按键1451");
                new Instrumentation().sendKeyDownUpSync(1451);
            } catch (Exception e) {
            }
        }).start();
    }


    /**
     * 开始扫描
     */
    public void startScan() {
        if (!DeviceHelper.getInstance().isReading()) changeScanState();
    }

    /**
     * 更改扫描状态
     */
    public void changeScanState() {
        new Thread(() -> {
            try {
                System.out.println("发送虚拟按键300");
                new Instrumentation().sendKeyDownUpSync(300);
            } catch (Exception e) {
            }
        }).start();
    }


    /**
     * 如果需要下次还能扫的同时停止扫描功能，调用这个方法
     * 清除缓存
     */

    public void cleanRFIDCache() {
        stopScan();
        Optional.ofNullable(getCacheKey()).ifPresent(cacheTag -> {
            new Handler().postDelayed(() -> {
                DeviceHelper.getInstance().cleanCache(cacheKey);
            }, 30);
        });
    }

    @Override

    public void cleanRFIDCache(String key) {
        stopScan();
        Optional.ofNullable(key).ifPresent(cacheTag -> {
            new Handler().postDelayed(() -> {
                DeviceHelper.getInstance().cleanCache(cacheTag);
            }, 30);
        });
    }


    @Override
    public void cleanRFIDCacheNotStop() {
        Optional.ofNullable(getCacheKey()).ifPresent(cacheTag -> {
            new Handler().postDelayed(() -> {
                DeviceHelper.getInstance().cleanCache(cacheKey);
            }, 30);
        });
    }

    @Override
    public void playOtherSound() {
        DeviceHelper.getInstance().playOhterVoice();
    }


    public void changeModelCache(AnalyzeImpl analyze) {
        RxBus.getDefault().postSticky(analyze);
    }
}
